#!/usr/local/bin/perl -w
########################################################################
#Search a directory for all .Scope files/globs
#Crunch the data in all .Scope files into one .csv file
########################################################################

my @scope;
$DMT_DBG = 0;
sub process_dir
{
	my $dir = shift;

	opendir(THISDIR, $dir) or die "Can't Open directory $dir - $!\n";
	my @listing = readdir THISDIR;
	closedir THISDIR;
	@listing = map { $dir . "\\" . $_ } @listing;
	print "<directory listing>\n\t";
	print join( "\n\t", @listing ,"WEINA IS A MONKEY!\n" );
	print "\n</directory_listing>\n\n";
	foreach my $item ( @listing )
	{
		if( -d $item )
		{
			print "$item is a directory\n";
			
			process_dir( $item ) if( $item !~ /\\.{1,2}$/ );
		}
		elsif( $item =~ /\.Scope$/ )
		{
			#$item =~ s/^.+:/\\Storage Card/;
			print "\t\t$item\n";
			push( @scope, $item );
		}
		elsif( $item !~ /^\./ )
		{
			print "$item is neither a directory nor an mp3 file\n";
		}
	}
	print "Done processing directory $dir\n";
#print @Files;
}

print "Starting to process $ARGV[ 0 ]\n";
process_dir( $ARGV[ 0 ] );
open MasterFile, ">$ARGV[ 1 ].csv";
$firstScopeFile_bar = 0;
$trackFileCount = 0;
$xmax = $ymax = 0;
$x = 0;
$y = 1;
foreach $entry ( @scope )
{
	if($DMT_DBG) 
	{
		print "Entering foreach loop to crunch scope files\n\t",$entry,"\n";
	}
	$StartWriting = 0;
	open MonkeyFile, "<$entry";
	while($data = <MonkeyFile>){
		#print $data;
		if( $data =~ /End Spectral Data/){
			$StartWriting = 0;
			if($DMT_DBG) 
			{
				print "End of Spectral Data\n";
			}
		}
		if($StartWriting){
			if(!$firstScopeFile_bar){
				@dataSplit = split /\s+/,$data;
				$specData[$x][0]= $dataSplit[0]; #wavelength
				$specData[$x][1]= $dataSplit[1]; #intesity
                #print $specData[$x][0],"\t",$specData[$x][1],"\n";	
				$x++;
				if($x > $xmax){
					$xmax = $x;
				}
			}
			else{
				#print "x",$x,"y",$y,"\n";
			    @dataSplit = split /\s+/,$data;
				$specData[$x][$y]= $dataSplit[1]; #intesity
			    $x++; 	
				if($x > $xmax){
					$xmax = $x;
				}
			}
		}
		if($data =~ /Begin Spectral Data/ ) {
			$StartWriting =  1;
			if($DMT_DBG) 
			{
				print "Begin of Spectral Data\n";
			}
		}
	}
	$x=0;
	$y++;
	if($y > $ymax){
		$ymax = $y;
	}
	$firstScopeFile_bar++;
	close MonkeyFile;
}
#Parsing file names to remove directory tree listing
foreach $file (@scope){
	@fName = split(/\\/,$file);	
	$file = substr(@fName[$#fName],0,-13);
}
#printing to main .csv file
print MasterFile "wavelength,",join(",",@scope,"\n");
for($x = 0; $x < $xmax; $x++ )
{
	for($y = 0; $y < $ymax; $y++ )
	{
		#print "x",$x,"y",$y,"\n";
		print MasterFile $specData[$x][$y];
		if($y != $ymax-1){
			print MasterFile ",";
		}
	
	}
	print MasterFile "\n";
}
close MasterFile;

